<template>
  <div >
    <!-- class="facility-list-container" -->
    <!-- 筛选区 -->
    <el-card shadow="never" class="mb-6 border-box">
    <div class="filter-section ">
      <el-row :gutter="16" class="w-full flex-wrap items-center">
        <el-col :xs="24" :sm="12" :md="8" :lg="6">
          <el-input
            v-model="searchValue"
            placeholder="搜索设施..."
            class="search-input"
            :prefix-icon="Search"
            clearable
            @input="handleSearch"
          />
        </el-col>
        <el-select v-model="facilityType" placeholder="全部类型" class="filter-select">
          <el-option label="全部类型" value="" />
          <el-option
            v-for="item in facilityTypeOptions"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>

        <el-col :lg="6" :md="12" :sm="8" :xs="6">
          <div class="custom-segmented flex justify-end">
            <el-dropdown @command="filterByStatusDropdown" trigger="click">
              <el-button type="default">
                {{ statusFilterLabel }}
                <el-icon>
                  <ArrowDown />
                </el-icon>
              </el-button>
              <template #dropdown>
                <el-dropdown-menu>
                  <el-dropdown-item command="all">全部状态</el-dropdown-item>
                  <el-dropdown-item command="open">开放中</el-dropdown-item>
                  <el-dropdown-item command="part">部分维护</el-dropdown-item>
                  <el-dropdown-item command="maintenance">维护中</el-dropdown-item>
                  <el-dropdown-item command="closed">已关闭</el-dropdown-item>
                </el-dropdown-menu>
              </template>
            </el-dropdown>
          </div>
        </el-col>
        <el-col :xs="4" :sm="0" :md="6" :lg="6">
          <!-- 占位用，确保在小屏幕上不显示 -->
        </el-col>
        <el-col :xs="24" :sm="24" :md="24" :lg="2" class="mt-4 sm:mt-0 flex justify-end">
          <el-button class="ml-auto" type="primary" @click="toAddFacility">
            <el-icon>
              <Plus />
            </el-icon>
            添加设施
          </el-button>
        </el-col>
        </el-row>
      </div>
    </el-card>
      <!-- 顶部统计卡片 -->
      <!-- <div class="stats-cards">
      <div class="card">
        <div class="card-title">总设施数</div>
        <div class="card-value">{{ total }}</div>
      </div>
      <div class="card">
        <div class="card-title">开放中</div>
        <div class="card-value green">{{ open }}</div>
      </div>
      <div class="card">
        <div class="card-title">维护中</div>
        <div class="card-value orange">{{ maintenance }}</div>
      </div>
      <div class="card">
        <div class="card-title">部分维护</div>
        <div class="card-value gray">{{ part }}</div>
      </div>
    </div> -->
      <!-- 数据统计卡片 -->
      <div class="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-4 mb-6">
      <!-- 总设施数 -->
      <el-card
        class="stats-card border-box h-full bg-gradient-to-r from-blue-50 to-blue-100 dark:from-blue-900 dark:to-blue-800"
      >
        <div class="flex items-center">
          <div class="p-2 rounded-full bg-blue-500 text-white mr-4 flex-shrink-0">
            <i class="i-carbon-building text-2xl"></i>
          </div>
          <div class="flex-1 min-w-0">
            <div class="text-gray-500 text-sm truncate">总设施数</div>
            <CountTo class="stats-card__count text-xl font-bold truncate" :endVal="total" :duration="1000"></CountTo>
          </div>
        </div>
      </el-card>

      <!-- 开放中 -->
      <el-card
        class="stats-card border-box h-full bg-gradient-to-r from-green-50 to-green-100 dark:from-green-900 dark:to-green-800"
      >
        <div class="flex items-center">
          <div class="p-2 rounded-full bg-green-500 text-white mr-4 flex-shrink-0">
            <i class="i-carbon-checkmark-outline text-2xl"></i>
          </div>
          <div class="flex-1 min-w-0">
            <div class="text-gray-500 text-sm truncate">开放中</div>
              <CountTo  class="stats-card__count text-xl font-bold truncate" :endVal="open" :duration="1000"></CountTo>
          </div>
        </div>
      </el-card>

      <!-- 维护中 -->
      <el-card
        class="stats-card border-box h-full bg-gradient-to-r from-orange-50 to-orange-100 dark:from-orange-900 dark:to-orange-800"
      >
        <div class="flex items-center">
          <div class="p-2 rounded-full bg-orange-500 text-white mr-4 flex-shrink-0">
            <i class="i-carbon-tool-box text-2xl"></i>
          </div>
          <div class="flex-1 min-w-0">
            <div class="text-gray-500 text-sm truncate">维护中</div>
            <CountTo class="stats-card__count text-xl font-bold truncate" :endVal="maintenance" :duration="1000"></CountTo>
          </div>
        </div>
      </el-card>

      <!-- 部分维护 -->
      <el-card
        class="stats-card border-box h-full bg-gradient-to-r from-yellow-50 to-yellow-100 dark:from-yellow-900 dark:to-yellow-800"
      >
        <div class="flex items-center">
          <div class="p-2 rounded-full bg-yellow-500 text-white mr-4 flex-shrink-0">
            <i class="i-carbon-warning-alt text-2xl"></i>
          </div>
          <div class="flex-1 min-w-0">
            <div class="text-gray-500 text-sm truncate">部分维护</div>
            <CountTo class="stats-card__count text-xl font-bold truncate" :endVal="part" :duration="1000"></CountTo>
          </div>
        </div>
      </el-card>
    </div>
    <!-- 表格 -->
    <el-card shadow="never" class="border-box">
    <el-table 
      v-loading="isLoading"
      :data="tableData" 
      class="facility-table" 
      v-if="!showEmpty"
      height="calc(100vh - 460px)">
      <el-table-column prop="name" label="设施名称" min-width="180">
        <template #default="scope">
          <div class="facility-info">
            <span class="icon-wrapper">
              <img
                v-if="getFacilityIcon(scope.row.facilityType)"
                :src="getFacilityIcon(scope.row.facilityType)"
                class="w-6 h-6"
              />
            </span>
            <div>
              <div>{{ scope.row.facilityName }}</div>
              <div class="facility-code">编号：{{ scope.row.id }}</div>
            </div>
          </div>
        </template>
      </el-table-column>
      <el-table-column prop="type" label="类型" min-width="100">
        <template #default="scope">
          <div class="facility-type" v-if="scope.row.facilityType">{{
            getFacilityStatus(scope.row.facilityType)
          }}</div>
          <div class="facility-type" v-else>未知设备</div>
        </template>
      </el-table-column>
      <el-table-column prop="location" label="位置" min-width="120" />
      <el-table-column prop="operationStatus" label="状态" min-width="80">
        <template #default="scope">
          <el-tag :type="getStatusType(scope.row.operationStatus)" effect="plain">
            {{ getDisplayStatus(scope.row.operationStatus) }}
          </el-tag>
        </template>
      </el-table-column>
      <!-- <el-table-column prop="lastCheck" label="上次检修" min-width="120" /> -->
      <el-table-column label="操作" min-width="180">
        <template #default="scope">
          <el-button type="info" size="small" link @click="viewDetail(scope.row)">
            <el-icon><View /></el-icon>
            详情
          </el-button>
          <el-button type="primary" size="small" link @click="editFacility(scope.row)">
            <el-icon><Edit /></el-icon>
            编辑
          </el-button>
        </template>
      </el-table-column>
    </el-table>


    <!-- 空状态 -->
    <div class="h-[calc(100vh-450px)]" v-if="showEmpty">
      <el-empty description="暂无设施数据" />
    </div>
    <!-- 分页器 -->
    <div class="flex justify-center mt-5">
      <el-pagination
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :page-sizes="[10, 20, 50, 100]"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total1"
        :hide-on-single-page="false"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>
    </el-card>
  </div>
</template>

<script setup>
  import { ref } from 'vue'
  import { Plus, Search } from '@element-plus/icons-vue'
  import { useRouter } from 'vue-router'
  import { CountTo } from 'vue3-count-to'
  import {
    scenicScenicSpotFacilityPageScenicSpotFacilityUsingPost,
    dictApiListDictByTypeUsingPost,
    scenicScenicSpotFacilityCountFacilityStatusUsingPost
  } from '@/api/4a'
  const searchValue = ref('')
  // const type = ref('')
  const status = ref('')
  // 分页相关
  const currentPage = ref(1)
  const pageSize = ref(10)
  const isLoading = ref(true)
  const facilityType = ref(undefined)
  const facilityTypeOptions = ref()
  const formRef = ref({

    belongId: undefined, // 所属景点（景点id）
    belongType: 1, // 设备类型
    facilityName: '', // 设备名称 搜索
    operationStatus: undefined, // 运营状态
    facilityType: undefined
  })
  // 设备状态
  let total = ref(0)
  let total1 = ref(0)
  let open = ref(0)
  let maintenance = ref(0)
  let part = ref(0)
  const tableData = ref([])
  const router = useRouter()
  const statusFilterLabel = ref('全部状态')
  const statusMap = {
    1: '开放中',
    2: '部分维护',
    3: '维护中',
    4: '已关闭'
  }
  const facilityMap = {
    1: '卫生间',
    2: '消防栓',
    3: '摄像头',
    4: '地铁',
    5: '出入口',
    6: '娱乐设施',
    7: '公交站',
    8: '停车场',
    9: '安全防护',
    10:'购物',
    11:'医务室'
  }
  const facilityIconMap = []

  const statusFilterMap = {
    all: '',
    open: 1,
    part: 2,
    maintenance: 3,
    close: 4
  }

  // 空状态判断
  const showEmpty = computed(() => {
    return tableData.value.length === 0 && !isLoading.value
  })
  // 获取设备数据
  const getFacilityList = async () => {
    isLoading.value = true
    try {
      const res = await scenicScenicSpotFacilityPageScenicSpotFacilityUsingPost({
        body: {
          ...formRef.value,
          current: currentPage.value,
          size: pageSize.value
        }
      })
      if (res.code === 0) {
        tableData.value = res.data.list
        status.value = res.data.list.operationStatus
        total1.value = res.data.total
      }
    } catch {
      ElMessage.error('获取设备列表失败')
    } finally {
      isLoading.value = false
    }
  }
  const handleSearch = () => {
    // 搜索逻辑
    formRef.value.facilityName = searchValue.value
    getFacilityList()
    getFacilityNum()
  }
  const toAddFacility = () => {
    // 跳转新增设施
    router.push('/facility/facility-edit')
  }
  const viewDetail = (item) => {
    // 查看详情
    router.push({
      path: '/facility/facility-detail',
      query: { id: item.id }
    })
  }
  const editFacility = (item) => {
    // 编辑
    router.push({
      path: '/facility/facility-edit',
      query: { id: item.id }
    })
  }
  // 获取设备的状态统计
  const getFacilityNum = async () => {
    const res = await scenicScenicSpotFacilityCountFacilityStatusUsingPost({
      body: {
        applyUser: null,
        belongId: null,
        facilityName: '',
        belongType: null,
        current: null,
        facilityType: null,
        operationStatus: null,
        size: null
      }
    })
    if (res.code === 0) {
      open.value = res.data[1] || 0
      maintenance.value = res.data[2] || 0
      part.value = res.data[3] || 0
      // total = computed(() => {
      //   return open.value + maintenance.value + part.value
      // })
      total.value = open.value + maintenance.value + part.value
    }
  }
  // 获取设施类型
  const getFacilityType = async () => {
    const res = await dictApiListDictByTypeUsingPost({ body: ['95210'] })
    if (res.code === 0) {
      const list = res.data[0].dictDataList
      facilityTypeOptions.value = res.data[0].dictDataList.map((item) => ({
        label: item.dictLabel,
        value: item.dictValue
      }))
      // 构建图标映射：value -> icon class name
      list.forEach((item) => {
        // 假设 dictMark 存储的是图标类名，如 "toilet" -> iconsys-toilet
        facilityIconMap[item.dictValue] =
          `${item.dictRemark}` ||
          'https://xibuyj.com/school/file/training/training/20250514/9964e9287c2848fe9dbfac6f4e6fe5e9wc (1).png'
      })
    } else {
      facilityTypeOptions.value = []
    }
  }
  const filterByStatusDropdown = (command) => {
    const selectedFilter = command
    if (command === 'closed') {
      formRef.value.operationStatus = 4
    } else {
      formRef.value.operationStatus = statusFilterMap[selectedFilter]
    }
    currentPage.value = 1
    getFacilityList()
    getFacilityNum()
    // 更新按钮显示文本
    const labelMap = {
      all: '全部状态',
      open: '开放中',
      part: '部分维护',
      maintenance: '维护中',
      closed: '已关闭'
    }
    statusFilterLabel.value = labelMap[command] || '未知'
  }

  const getStatusType = (status) => {
    switch (status) {
      case 1:
        return 'success'
      case 2:
        return 'warning'
      case 3:
        return 'info'
      case 4:
        return 'danger'
      default:
        return ''
    }
  }

  const getFacilityIcon = (type) => {
    return facilityIconMap[type] || '' // 默认图标
  }
  const getDisplayStatus = (status) => {
    return statusMap[status] || '未知'
  }
  const getFacilityStatus = (status) => {
    return facilityMap[status] || '未知设备'
  }

  // 处理页码大小变化
  const handleSizeChange = (val) => {
    pageSize.value = val
    currentPage.value = 1
    getFacilityList()
  }
  // 处理页码变化
  const handleCurrentChange = (val) => {
    currentPage.value = val
    getFacilityList()
  }
  onMounted(async () => {
    getFacilityNum()
    getFacilityList()
    await getFacilityType()
    filterByStatusDropdown('all') // 默认加载全部数据
  })
  onBeforeRouteUpdate((to, from, next) => {
    getFacilityList()
    getFacilityNum()
    next()
  })

  watch(
    () => facilityType.value,
    () => {
      if (facilityType.value === 0) {
        facilityType.value = undefined
      } else {
        formRef.value.facilityType = facilityType.value
      }
      getFacilityList()
      getFacilityNum()
    }
  )
</script>

<style scoped>
  .facility-list-container {
    min-height: 100vh;
    padding: 24px;
    background: #fff;
    border-radius: 10px;
  }

  .filter-section {
    /* margin-bottom: 24px; */
  }

  .filter-section .el-input,
  .filter-section .el-dropdown {
    width: 100%;
  }

  .stats-cards {
    display: flex;
    gap: 24px;
    margin-bottom: 24px;
  }

  .card {
    position: relative;
    display: flex;
    flex: 1;
    flex-direction: column;
    align-items: flex-start;
    padding: 18px 24px;
    background: #f7fafd;
    border-radius: 8px;
  }

  .card-title {
    margin-bottom: 8px;
    font-size: 14px;
    color: #888;
  }

  .card-value {
    font-size: 28px;
    font-weight: bold;
    color: #222;
  }

  .card-value.green {
    color: #1abc1a;
  }

  .card-value.orange {
    color: #ff9800;
  }

  .card-value.gray {
    color: #888;
  }

  .card-icon {
    position: absolute;
    top: 18px;
    right: 18px;
    font-size: 28px;
    color: #e0e0e0;
  }

  .filter-select {
    width: 120px;
  }

  .filter-btn {
    color: #666;
    background: #f7fafd;
    border: none;
  }

  .search-input {
    width: 220px;
    margin-left: 0;
  }

  .facility-table {
    margin-top: 12px;
  }

  .facility-info {
    display: flex;
    gap: 12px;
    align-items: center;
  }

  .facility-code {
    font-size: 12px;
    color: #888;
  }

  .pagination {
    display: flex;
    justify-content: flex-end;
    margin-top: 16px;
  }

  .icon-wrapper {
    display: flex;
    align-items: center;
    justify-content: center;
    width: 40px;
    height: 40px;
    margin-right: 12px;
    background-color: #f0f4ff; /* 浅蓝色背景 */
    border-radius: 50%;
  }

  .facility-icon {
    margin-right: 10px;
    font-size: 20px;
    color: #409eff;
  }
  .stats-card {
    cursor: pointer;
    box-shadow: none;
    transition: transform 0.2s ease;

    &:hover {
      transform: translateY(-2px)
    }
  }
  .border-box {
    border-radius: 8px !important;
  }
</style>
